<?php


namespace App\Http\Controllers\User;
use App\Models\User\Address;
use App\Models\User\Collection;
use App\Models\User\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Validator;
/**
 * @group 用户信息
 *
 * 采用 restful api
 *
 * Body Parameters 表示请求的所需要的参数
 *
 * Query Parameters 表示返回参数的名称
 */
class UserInfoController extends Controller
{
    /**
     * 用户信息查看
     *
     * @queryParam  name 姓名
     * @queryParam  phone 手机号
     * @queryParam  card 身份证
     * @queryParam  hospital_id 住院号
     * @queryParam  card 身份证
     * @queryParam  carte_card 用户社保卡
     * @queryParam  medical_card 用户就诊卡
     * @queryParam  register_id 登记号
     * @queryParam  address->address->address 地址
     * @queryParam  image 图片
     * @queryParam  family_name 用户家属姓名
     * @queryParam  family_phone 用户家属电话
     * @queryParam  family_wechat 用户家属微信号
     *
     * @bodyParam search string 姓名
     * @bodyParam address string 地址
     * @bodyParam hospital_id int 住院号
     * @bodyParam card int 身份证号
     *
     */
    public function index(Request $request){
        $type=$request->user_type;
        if ($type==1){
            $id=$request->user_id;
            $data = User::with('address')->with('image')->with('collection')->find($id);
            unset($data['password']);
            return response()->json($data,200);
        }
        $query = User::with('address')->with('image')->where(function ($q) use($request){
            $request->has('search') && $q->where('name','like',"%{$request->get('search')}%");
            $request->has('card') && $q->where('card','like',"%{$request->get('card')}%");
            $request->has('hospital_id') && $q->where('hospital_id','like',"%{$request->get('hospital_id')}%");
        })->whereHas('address',function ($query) use($request){
            $request->has('address') && $query->where('address','like',"%{$request->get('address')}%");
        });
            return response()->json(pageQuery($query,$request),200);

    }
    /**
     * 用户信息查看单条
     *
     * @queryParam  name 姓名
     * @queryParam  phone 手机号
     * @queryParam  card 身份证
     * @queryParam  hospital_id 住院号
     * @queryParam  card 身份证
     * @queryParam  carte_card 用户社保卡
     * @queryParam  medical_card 用户就诊卡
     * @queryParam  register_id 登记号
     * @queryParam  address->address->address 地址
     * @queryParam  image 图片
     * @queryParam  family_name 用户家属姓名
     * @queryParam  family_phone 用户家属电话
     * @queryParam  family_wechat 用户家属微信号
     * @queryParam  collection 用户收藏
     *
     */
    public function show(Request $request,$pk){
        $type=$request->user_type;

        $data = User::with('address')->with('image')->with('collection')->find($pk);
        if($data == []){
            return response()->json(["message"=>"没有该信息"],404);
        }else{
            return response()->json($data,200);
        }
    }
    /**
     * 用户信息添加
     *
     *
     * @bodyParam name string required 姓名
     * @bodyParam password string required 密码
     * @bodyParam phone string required 手机号
     * @bodyParam card  string required 身份证
     * @bodyParam hospital_id int required 住院号
     * @bodyParam card  int required 身份证
     * @bodyParam register_id int required 登记号
     * @bodyParam carte_card int required 用户社保卡
     * @bodyParam medical_card int required 用户就诊卡
     * @bodyParam image string required 头像
     * @bodyParam family_name string 用户家属姓名
     * @bodyParam family_phone  string 用户家属电话
     * @bodyParam family_wechat  string 用户家属微信号
     * @bodyParam address json 地址  [{"address": "长111沙11区"},{"address":"s2adfx"}]
     *
     * 425 添加用户失败
     * 426 添加地址失败
     * 503 添加失败
     */
    public function store(Request $request){
//        $e = genValidate();
//        $validator = Validator::make($request->all(),$e);
//        if($validator->fails()){
//            return response()->json(encodeMsg($validator->errors()->messages(),400),400);
//        }
        try{
            $data=$request->all();
            if ($request->get('phone')!=null){
               $row= User::where('phone',$request->get('phone'))->first();
               if ($row!=[]){
                   return response()->json(["message"=>"手机号重复"],421);
               }
            }
//            if ($data['password']!=null){
//                $pas=md5($data['password']);
//                $data['password']=$pas;
//            }
            DB::beginTransaction();
            if (!empty($data['address'])){
                $address= json_decode($data['address'],true);
                unset($data['address']);
                $id=User::insertGetId($data);
                if (!$id){
                    return response()->json(["message"=>"添加用户失败"],425);
                }
                foreach($address as $k=>$v){
                    $address_id=Address::insertGetId(["address"=>$v['address'],"user_id"=>$id]);
                    if (!$address_id){
                        DB::rollBack();
                        return response()->json(["message"=>"添加地址失败"],426);

                    }
                }
                DB::commit();
                return response()->json(["message"=>"添加成功"],201);
            }
            User::create($data);
            return response()->json(["message"=>"添加成功"],201);
        }catch (QueryException $e){
            DB::rollBack();
            return response()->json($e->getMessage(),503);
        }
    }
    /**
     * 用户信息修改
     *
     * @bodyParam name string 姓名
     * @bodyParam password string 密码
     * @bodyParam phone string 手机号
     * @bodyParam card  string 身份证
     * @bodyParam hospital_id int 住院号
     * @bodyParam card  int 身份证
     * @bodyParam register_id int 登记号
     * @bodyParam carte_card int 用户社保卡
     * @bodyParam medical_card int 用户就诊卡
     * @bodyParam image string 头像
     * @bodyParam family_name string 用户家属姓名
     * @bodyParam family_phone  string 用户家属电话
     * @bodyParam family_wechat  string 用户家属微信号
     *
     * @bodyParam address json地址
     * @bodyParam Collection json 收藏
     * address 举例:[{"address": "长沙11区"},{"id":"3","address":"sax"}]
     * address [{"address": "长沙11区"}] 添加地址
     * address [{"id":"3","address": "长沙11区"}] 修改地址
     * address[{"id":"4"}] 删除地址
     *
     * collection {"0":8} 删除收藏
     * collection {"1":{"business_id":9}} 添加收藏
     * 409 json格式错误
     * 410 添加地址失败
     * 412 删除地址失败
     * 413 修改地址失败
     * 415 修改数据失败
     * 503 修改失败
     */

    public function update(Request $request,$pk){

        $e = genValidate();
        $validator = Validator::make($request->all(),$e);
        if($validator->fails()){
            return response()->json(encodeMsg($validator->errors()->messages(),400),400);
        }
        if ($request->user_type == 1){
            $pk = $request->user_id;
        }
        $carkind = User::find($pk)->toArray();
        if($carkind == []){
            return response()->json(["message"=>"没有该信息"],404);
        }
        $data=$request->all();
        try {
            DB::beginTransaction();
            if(!empty($data['address'])){

                $address= json_decode($data['address'],true);
                unset($data['address']);
                if (!$address){return response()->json(["message"=>"json格式错误"],409);}
                foreach($address as $k=>$v){
                    if (empty($v['id'])){
                        $v=array(
                            'user_id'=>$pk,
                            'address'=>$v['address']
                        );
                        $id=Address::insertGetId($v);
                        if (!$id){
                            return response()->json(["message"=>"添加地址失败"],410);
                        }
                    }else{
                        if(empty($v['address'])){
                            $id_delete=Address::where('id',$v['id'])->delete();
                            if ($id_delete ==false){
                                DB::rollBack();
                                return response()->json(["message"=>"删除地址失败"],412);
                            }
                        }else{
                            $carstop=Address::where('id',$v['id'])->update($v);
                            if ($carstop ==false){
                                DB::rollBack();
                                return response()->json(["message"=>"修改地址失败"],413);
                            }
                        }
                    }
                }
                }
            if(!empty($data['collection'])){
                $collection= json_decode($data['collection'],true);
                if (!$collection){return response()->json(["message"=>"json格式错误"],409);}
                unset($data['collection']);
                foreach ($collection as $k=>$v){
                    if (!empty($v['business_id'])){
                        $v=array(
                            'user_id'=>$pk,
                            'business_id'=>$v['business_id']
                        );
                        $id=Collection::insertGetId($v);
                        if (!$id){
                            return response()->json(["message"=>"添加收藏失败"],410);
                        }
                    }else{
                        $v=array(
                            'user_id'=>$pk,
                            'business_id'=>$v,
                        );
                            $id_delete=Collection::where($v)->delete();
                            if ($id_delete ==false){
                                DB::rollBack();
                                return response()->json(["message"=>"删除收藏失败"],412);
                            }
                    }
                }
            }
            if ($data!=null){
                $up=User::where('id',$pk)->update($data);
                if ($up ==false){
                    DB::rollBack();
                    return response()->json(["message"=>"修改失败"],415);
                }
            }
            DB::commit();
            return response()->json(["message"=>"修改成功"],200);

        }catch (QueryException $e){
            DB::rollBack();
            return response()->json(["message"=>"修改失败"],503);
        }
    }
    /**
     * 用户信息删除
     *
     */

    public function destroy(Request $request,$pk){

        $data = User::find($pk);
        if($data == []){
            return response()->json(["message"=>"没有该信息"],404);
        }
        $data->delete();
        return response()->json(["message"=>"删除成功"],200);
    }
    /**
     * 用户删除（多个）
     *
     * @bodyParam  user_id json required  用户id {"0":{"id":23},"1":{"id":24}}
     *
     */
    public function alldelete(Request $request){
        $business=json_decode($request->get('user_id'),true);
        DB::beginTransaction();
        foreach ($business as $k=>$v){
            $data=User::find($v['id']);
            if($data == []){
                DB::rollBack();
                return response()->json(["message"=>"没有该信息"],404);
            }
            $data->delete();
        }
        DB::commit();
        return response()->json(["message"=>"删除成功"],200);
    }
}
